package com.cmcc.driver.ui.main.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmcc.driver.data.DriverDataRepository
import com.cmcc.driver.data.DriverRequest
import com.cmcc.driver.data.Network
import com.cmcc.driver.data.entity.Order
import com.cmcc.driver.data.entity.OrderDetail
import com.cmcc.driver.data.entity.OrderTemp
import com.cmcc.driver.data.entity.response.CarInfo
import com.cmcc.driver.data.entity.response.ResMsg
import com.cmcc.shared.config.SharedConfig
import com.cmcc.shared.model.AppResponse
import com.cmcc.shared.utils.L
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class OrderReceiveViewModel : ViewModel() {

    val orderList = MutableLiveData<List<Order>>()
    val orderReceiving = MutableLiveData<AppResponse<String>>()
    var orderDetail = MutableLiveData<OrderDetail>()
    var orderNumber = 0

    val direction = MutableLiveData<String>()
    val distance = MutableLiveData<String>()
    val duration = MutableLiveData<String>()

    var carInfo  = MutableLiveData<CarInfo>()

    var orderDoing = MutableLiveData<OrderDetail>()

    var isorderDoing = MutableLiveData<Boolean>()

    var orderDoingNetStatus = MutableLiveData<Boolean>()

    val resMsg = MutableLiveData<ResMsg>()

    val orderTemplate = MutableLiveData<OrderTemp>()

    private val refusalSuccess = MutableLiveData<AppResponse<Boolean>>()


    private val cancel = MutableLiveData<AppResponse<Boolean>>()

    private val _nextOrderState = MutableLiveData<String>()
    val nextOrderState: LiveData<String>
        get() = _nextOrderState

    fun receivingOrder(orderId: String): MutableLiveData<AppResponse<String>> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().receivingOrder(orderId)
                if(response.isSuccessful){
                    val post = response.body()
                    orderReceiving.value = post
                } else{
                    L.d("response error")
                }
            } catch (e : Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return orderReceiving
    }

    fun actionOrder(orderId: String):MutableLiveData<AppResponse<String>>{
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().receivingOrder(orderId)
                if(response.isSuccessful){
                    val post = response.body()
                    orderReceiving.value = post
                } else{
                    L.d("response error")
                }
            } catch (e : Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return orderReceiving
    }

    fun refusalOrder(orderId: String): MutableLiveData<AppResponse<Boolean>> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().refusalOrder(orderId)
                if (response.isSuccessful) {
                    val post = response.body()
                    refusalSuccess.value = post

                } else {
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return refusalSuccess
    }


    fun cancel(orderId: String): MutableLiveData<AppResponse<Boolean>> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().cancel(orderId)
                if (response.isSuccessful) {
                    val post = response.body()
                    cancel.value = post

                } else {
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return cancel
    }


    /**
     * 司机操作下一步
     */
    fun nextOrder(
        orderId: String, payMethod: Int, mileageFee: Double,
        durationFee: Double, totalAmount: Double, status: Int
    ) {
        _nextOrderState.postValue("loading")
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().nextOrder(
                    orderId, payMethod, mileageFee,
                    durationFee, totalAmount, status
                )
                if (response.isSuccessful) {
                    val post = response.body()
                    resMsg.value = ResMsg(post?.code ?: 0, post?.msg ?: "")
                    _nextOrderState.value = "success"
                } else {
                    _nextOrderState.value = "error"
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                _nextOrderState.value = "error"
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun nearbyOrder(latLng : LatLng) {

        viewModelScope.launch(Dispatchers.Main) {
            val response = DriverRequest.getInstance().nearbyOrder(latLng)
            try {
                orderDoingNetStatus.value = true
                if (response.isSuccessful) {
                    val posts = response.body()
                    orderList.value = posts?.data
                    orderDoingNetStatus.value = false
                } else {
                    orderDoingNetStatus.value = false
                    L.d("123")
                }
            } catch (e : Exception) {
                orderDoingNetStatus.value = false
            }
        }
    }

    /**
     * 获取车辆信息及driverId
     */
    fun requestCarInfo() :MutableLiveData<CarInfo>{
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().getCarInfo()
                if (response.isSuccessful) {
                    val body = response.body()
                    if (body?.data?.isNotEmpty() == true){
                        carInfo.value = body.data[0]
                    }
                } else {
                    L.d("response failed")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return carInfo
    }


    fun getOrderDetail(id: String):MutableLiveData<OrderDetail>{
        _nextOrderState.postValue("loading")
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().orderDetail(id)
                val response2 = DriverRequest.getInstance().orderNumber()
                if(response2.isSuccessful){
                    val body = response2.body()
                    orderNumber = body?.data?.toInt() ?: 0
                }
                if(response.isSuccessful){
                    val body = response.body()
                    orderDetail.value = body?.data
                    _nextOrderState.value = "success"
                }else {
                    _nextOrderState.value = "error"
                }
            } catch (e : Exception) {
                L.d("e :" + e.message + "," + e.cause)
                _nextOrderState.value  = "error"
            }
        }
        return orderDetail
    }


    /**
     * 获取订单模板
     */
    fun getOrderTemplate(id: String): MutableLiveData<OrderTemp> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().getOrderTemplate(id)
                if (response.isSuccessful) {
                    val data = response.body()
                    orderTemplate.value = data?.data
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return orderTemplate
    }

    fun getDirection(origin: String, destination: String) {
        viewModelScope.launch(Dispatchers.Main) {

            try {
                val response = Network.getInstance().googleApiService.getDirection(origin, destination).await()
                if (response.isSuccessful) {
                    val posts = response.body()
                    if (!posts?.routes.isNullOrEmpty()) {
                        distance.value = posts?.routes?.get(0)?.legs?.get(0)?.distance?.text
                        duration.value = posts?.routes?.get(0)?.legs?.get(0)?.duration?.text
                        direction.value = posts?.routes?.get(0)?.overview_polyline?.points
                    }
                } else {
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    /**
     * 查询正在进行的订单
     */
    fun queryOrderProgress() : MutableLiveData<OrderDetail> {
        _nextOrderState.postValue("loading")
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().queryOrderInProgress()
                if(response.isSuccessful){
                    val post = response.body()
                    orderDoing.value = post?.data
                    if (post?.data == null) {
                        isorderDoing.value = false
                    }else {
                        if (post?.data.status in 1..5) {
                            isorderDoing.value = true
                            SharedConfig.isorderDoing = true
                        }else {
                            SharedConfig.isorderDoing = false
                        }
                    }
                    _nextOrderState.value = "success"
                }else{
                    _nextOrderState.value = "error"
                }
            } catch (e : Exception) {
                L.d("e :" + e.message + "," + e.cause)
                _nextOrderState.value = "error"
            }
        }
        return orderDoing
    }

    fun hasStatusChange():MutableLiveData<Boolean>{
        return DriverDataRepository.getInstance().hasStatusChange()
    }
}